package com.XZDP.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.XZDP.dto.UserDTO;
import com.XZDP.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class MyUtils {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 生成token并将MAP集合加入redis
     *
     * @param user
     * @param redisTemplate
     * @return
     */
    public String TokenAndToRedis(User user, StringRedisTemplate redisTemplate) {
        //session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        //将session切换为redis实现登录校验功能
        //将用户信息存储到redis并且返回前端token
        //生成随机token作为存储用户信息的key
        String token = RandomUtil.randomString(5);
        //将user转换为userDTO
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将 userDTO转为MAP
        Map<String, Object> map = BeanUtil.beanToMap(userDTO);
        //解决字符串序列化问题
        Map<String, String> StringMap = ReturnStringMap(map);
        //用token作为key存储到redis,并设置过期时间为30分钟---使用HashMap数据结构
        redisTemplate.opsForHash().putAll("User:" + token, StringMap);
        redisTemplate.expire(token, Duration.ofMinutes(30));
        return token;
    }


    /**
     * 本项目序列化使用
     * 传入一个MAP集合，将其转成<String,String>形式返回
     */
    public Map<String, String> ReturnStringMap(Map<String, Object> map) {
        Map<String, String> StringMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                StringMap.put(key, value.toString());
            } else {
                StringMap.put(key, null);
            }
        }
        return StringMap;
    }

    /**
     * 尝试获取互斥锁
     */
    public Boolean tryGetLock(String key) {
        Boolean b = redisTemplate.opsForValue().setIfAbsent(key, "1", 1, TimeUnit.MINUTES);
        //预防自动拆箱导致空指针异常
        return Boolean.TRUE.equals(b);
    }

    /**
     * 释放互斥锁
     */
    public void CloseLock(String key) {
        redisTemplate.delete(key);
    }
}
